import {
  config
} from 'config.js';

class Token {
  constructor() {
    this.verifyUrl = config.baseUrl + 'oauth/verify';
    this.tokenUrl = config.baseUrl + 'oauth/token';
    this.updateUrl = config.baseUrl + 'oauth/update';
  }

  verify() {
    return new Promise((resolve, reject) => {
      let token = wx.getStorageSync('token');
      if (!token) {
        this.getTokenFromServer(resolve, reject);
      } else {
        this._veirfyFromServer(resolve, reject, token);
      }
    });
  }

  /**
   * 更新用户信息
   * @param {String} token 
   * @param {Object} user 
   */
  updateUserInfo(user) {
    var that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: that.updateUrl,
        method: 'POST',
        data: {
          token: wx.getStorageSync('token'),
          user: user
        },
        success: function (res) {
          const code = res.statusCode.toString();
          if (code.startsWith('2')) {
            wx.setStorageSync('oauth', res.data.data);
            resolve(res.data.data);
          } else {
            that._show_error('用户授权失败');
          }
        },
        fail: (err) => {
          reject();
          that._show_error(err.msg);
        }
      });
    });
  }

  // 携带令牌去服务器校验令牌
  _veirfyFromServer(resolve, reject, token) {
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method: 'POST',
      data: {
        token: token
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var valid = res.data;
        if (!valid) {
          that.getTokenFromServer(resolve, reject);
        } else {
          resolve(true);
        }
      },
      fail: (err) => {
        reject(false);
        that._show_error(err.msg);
      }
    })
  }

  //从服务器获取token
  getTokenFromServer(resolve, reject) {
    var that = this;
    wx.login({
      success: function (res) {
        wx.request({
          url: that.tokenUrl,
          method: 'POST',
          data: {
            code: res.code
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            const code = res.statusCode.toString();
            if (code.startsWith('2')) {
              wx.setStorageSync('token', res.data.token);
              wx.setStorageSync('oauth', res.data.oauth);
              resolve(true);
            } else {
              reject(false);
              that._show_error();
            }
          },
          fail: (err) => {
            reject(false);
            that._show_error(err.msg);
          }
        })
      }
    })
  }

  _show_error(msg) {
    let tip = !msg ? '抱歉，出现了错误' : msg;
    wx.showToast({
      title: tip,
      icon: 'none',
      duration: 2000
    });
  }
}

export {
  Token
}